/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.angis.xiugallery.image.util;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import cc.angis.xiugallery.BuildConfig;

/**
 * A simple subclass of {@link ImageResizer} that fetches and resizes images fetched from a URL.
 */
public class ImageDetailLoader extends ImageResizer {
    private static final String TAG = "ImageLoader";

    /**
     * Initialize providing a target image width and height for the processing images.
     *
     * @param context
     * @param imageWidth
     * @param imageHeight
     */
    public ImageDetailLoader(Context context, int imageWidth, int imageHeight) {
        super(context, imageWidth, imageHeight);
    }

    /**
     * Initialize providing a single target image size (used for both width and height);
     *
     * @param context
     * @param imageSize
     */
    public ImageDetailLoader(Context context, int imageSize) {
        super(context, imageSize);
    }

    /**
     * The main process method, which will be called by the ImageWorker in the AsyncTask background
     * thread.
     *
     * @param data The data to load the bitmap, in this case, a regular http URL
     * @return The downloaded and resized bitmap
     */
    private Bitmap processBitmap(String data) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "processBitmap - " + data);
        }

        return initImages(mContext, data);
    }

    @Override
    protected Bitmap processBitmap(Object data) {
        return processBitmap(String.valueOf(data));
    }

 
    private Bitmap initImages(Context context, String matchkey) {
    	
//    	final File cacheDir = DiskLruCache.getDiskCacheDir(context, FOLDER_CACHE_DIR);
//
//        final DiskLruCache cache =
//                DiskLruCache.openCache(context, cacheDir, FOLDER_CACHE_SIZE);
//
//        final File cacheFile = new File(cache.createFilePath(matchkey));
//
//        if (cache.containsKey(matchkey)) {
//            if (BuildConfig.DEBUG) {
//                Log.d(TAG, "downloadBitmap - found in folder cache - " + matchkey);
//            }
//            return cacheFile;
//        }

        if (BuildConfig.DEBUG) {
            Log.d(TAG, "loadBitmap - loading - " + matchkey);
        }
        try{
				String[] projection = new String[]{
			            MediaStore.Images.Media.DATA,
			            MediaStore.Images.Media.ORIENTATION,
			    };

			    // Get the base URI for the People table in the Contacts content provider.
			    Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

			    // Make the query.
			    Cursor cur = context.getContentResolver().query(images,
			            projection, // Which columns to return
			            MediaStore.Images.Media._ID+ "=?",         // Which rows to return (all rows)
			            new String[]{matchkey},       // Selection arguments (none)
			            null        // Ordering
			            );

			    Log.i("ListingImages"," query count="+cur.getCount());
			    String imageData = null;
			    int orientation = 0;
			    if (cur.moveToFirst()) {
			    	
			        int imageDataColumn = cur.getColumnIndex(
			            MediaStore.Images.Media.DATA);
			        int orientationColumn = cur.getColumnIndex(
			        		MediaStore.Images.Media.ORIENTATION);

			        do {
			            // Get the field values
			        	imageData = cur.getString(imageDataColumn);
			        	orientation = cur.getInt(orientationColumn);
//			            Log.i("ListingImages", " bucket=" + bucket 
//			                   + "  date_taken=" + date);
			        } while (cur.moveToNext());

			    }
			    cur.close();
		        
		        Bitmap bitmap = decodeSampledBitmapFromFile(imageData, mImageWidth, mImageHeight,orientation);
		        Bitmap result = ThumbnailUtils.extractThumbnail(bitmap, mImageWidth, mImageHeight);
		        
		        if (!bitmap.isRecycled()){
		        	bitmap.recycle();
		        	bitmap = null;
		        }
		        
		        return result;
			    
        }catch(Exception e){
        	return null;
        }
	}
}
